package system

import (
	"fmt"
	"os"
	"strings"
	"tyjt-ferry/database/orm"
)

func InitDB() error {
	filePath := "config/db.sql"
	sqlList, err := Ioutil(filePath)
	if err != nil {
		fmt.Println("数据库基础数据初始化脚本读取失败，原因：", err.Error())
		return err
	}
	for _, sql := range sqlList {
		err = orm.Eloquent.Exec(sql).Error
		if err != nil {
			return err
		}
	}
	return nil
}

func Ioutil(pathname string) ([]string, error) {
	data, err := os.ReadFile(pathname)
	if err != nil {
		return nil, err
	}
	lines := strings.Split(string(data), "\n")
	var cleanlines []string
	//  这里默认每一条sql语句为一行
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" || strings.HasPrefix(line, "--") {
			continue
		}
		cleanlines = append(cleanlines, line)
	}
	return cleanlines, nil
}
